import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { User, UserDocument } from 'src/model/user.schema';
import { CreateUserDto } from './dto/create-user.dto';
import { SearchUserDto } from './dto/search-user.dto';
import { pswToMd5 } from 'src/utils/md5';

@Injectable()
export class UserService {
  constructor(
    @InjectModel(User.name)
    private userModel: Model<UserDocument>,
  ) {}

  // 根据用户名查找
  async findOneByName(username: string) {
    return await this.userModel.findOne({ username }).exec();
  }

  //根据邮箱查找
  // async findOneByEmail(email: string) {
  //   return await this.userModel.findOne({ email });
  // }

  // 创建用户
  async createUser(createUserDto: CreateUserDto) {
    createUserDto.password = pswToMd5(createUserDto.password);
    return await this.userModel.create(createUserDto);
  }

  // 查找用户列表
  async findUserList() {
    return await this.userModel.find({});
  }

  // 条件搜索用户
  async findUserByNameOrEmail(searchUserDto: SearchUserDto) {
    const { searchSelect, searchUser } = searchUserDto;
    // let userList: User[];
    const reg = new RegExp(searchUser);
    const searchKey = searchSelect;
    // const level = roleLevel.split('-')[0];
    // if (level === '3' || level === '4') {
    //   userList = await this.userModel.find({
    //     [searchKey]: reg,
    //     roleLevel: new RegExp('^' + level),
    //   });
    // } else if (level === '2') {
    //   userList = await this.userModel.find({
    //     [searchKey]: reg,
    //     roleLevel: new RegExp('^' + level + '|4'),
    //   });
    // } else {
    const userList = await this.userModel.find({
      [searchKey]: reg,
    });
    // }
    return userList;
  }

  // 删除用户
  async removeUser(username: string) {
    await this.userModel.deleteOne({ username });
  }

  // 更新头像
  async updateAvatar(username: string, avatarUrl: string): Promise<any> {
    return this.userModel.updateOne({ username, $set: { avatar: avatarUrl } });
  }
}
